package com.zjk.product.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjk.pojo.dto.ProductDTO;
import com.zjk.pojo.product.SearchItem;
import com.zjk.pojo.product.TbDict;
import com.zjk.pojo.product.TbProduct;
import com.zjk.pojo.product.TbProductImages;
import com.zjk.product.feign.DictFeignClient;
import com.zjk.product.mapper.ProductImagesMapper;
import com.zjk.product.mapper.ProductMapper;
import com.zjk.result.ResultResponse;
import com.zjk.utils.IdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: gfk
 * @create: 2022/11/1
 * @Description:
 * @FileName: ProductService
 * @History:
 * @自定义内容：
 */
@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired(required = false)
    private DictFeignClient dictFeignClient;

    @Autowired
    private ProductImagesMapper productImagesMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;


    public List<TbDict> getRepaymentWayList() {
        List<TbDict> repaymentWayList = dictFeignClient.getRepaymentWayList();

        return repaymentWayList;
    }

    public ResultResponse saveProductType(TbDict tbDict) {
        redisTemplate.delete("productTypeList");
        return dictFeignClient.saveProductType(tbDict);
    }

    public List<TbDict> getProductTypeList() {
        List<TbDict> redisProduct = (List<TbDict>) redisTemplate.opsForValue().get("productTypeList");
        if (redisProduct!=null){
             return redisProduct;
        }else {
            List<TbDict> productTypeList = dictFeignClient.getProductTypeList();
            redisTemplate.opsForValue().set("productTypeList",productTypeList);
            return productTypeList;
        }
    }

    @Transactional
    public ResultResponse save(ProductDTO productDTO) {
        TbProduct tbProduct = new TbProduct();
        BeanUtils.copyProperties(productDTO,tbProduct);
        tbProduct.setCreateTime(new Date());
        tbProduct.setUpdateTime(new Date());
        tbProduct.setStatus("0");
        productMapper.insert(tbProduct);
        List<TbProductImages> imagesList = productDTO.getImagesList();
        imagesList.forEach((tbProductImages)->{
            productImagesMapper.insert(tbProductImages);
        });
        return new ResultResponse(true,"添加成功");
    }


    public Page<TbProduct> list(Integer pageNo, Integer pageSize) {
        Page<TbProduct> page = new Page<>(pageNo,pageSize);
        Page<TbProduct> tbProductPage = productMapper.selectPage(page, Wrappers.emptyWrapper());
        return tbProductPage;
    }

    public ResultResponse submit(Integer id) {
        TbProduct tbProduct = productMapper.selectById(id);
        if (tbProduct.getStatus().equals("0")){//草稿状态
            tbProduct.setStatus("1");
        }
      productMapper.updateById(tbProduct);
        return new ResultResponse(true,"成功");
    }

    public ResultResponse cfoAudit(Integer id,boolean ok) {
        TbProduct tbProduct = productMapper.selectById(id);
        if (tbProduct.getStatus().equals("1")){//草稿状态
            tbProduct.setStatus(ok?"2":"3");
        }
      productMapper.updateById(tbProduct);
        return new ResultResponse(true,"cfo"+(ok?"审核成功":"审核失败"));
    }

    public ResultResponse ceoAudit(Integer id,boolean ok) {
        TbProduct tbProduct = productMapper.selectById(id);
        if (tbProduct.getStatus().equals("2")){//草稿状态
            tbProduct.setStatus(ok?"4":"5");

            if (ok==true){
                //默认交换机
                rabbitTemplate.convertAndSend("","Queue_audit","请求ceo审核",(message -> {
                    IdWorker idWorker = new IdWorker();
                    long messageId = idWorker.nextId();
                    message.getMessageProperties().setMessageId(String.valueOf(messageId));
                    return message;
                }));
            }
        }
      productMapper.updateById(tbProduct);
        return new ResultResponse(true,"cfo"+(ok?"审核成功":"审核失败"));
    }


    public List<SearchItem> findSearchItem(Map searchMap) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取最后同步的时间
        String lastSyncTime = (String) searchMap.get("lastSyncTime");
        //判断是全量同步 还是增量同步
        QueryWrapper<TbProduct> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(lastSyncTime)){
            queryWrapper.lambda().gt(TbProduct::getUpdateTime,lastSyncTime);
        }
        List<TbProduct> tbProducts = productMapper.selectList(queryWrapper);

        return   tbProducts.stream().map((tbProduct) -> {
            SearchItem searchItem = new SearchItem();
            BeanUtils.copyProperties(tbProduct, searchItem);

            switch (tbProduct.getPeriod()) {
                case "1":
                    searchItem.setPeriod("3期");
                    break;
                case "2":
                    searchItem.setPeriod("6期");
                    break;
                case "3":
                    searchItem.setPeriod("12期");
                    break;
            }
            switch (tbProduct.getRateUnit()) {
                case "1":
                    searchItem.setRateUnit("年息");
                    break;
                case "2":
                    searchItem.setRateUnit("月息");
                    break;
                case "3":
                    searchItem.setRateUnit("日息");
                    break;
            }
            String productType = tbProduct.getProductType();
            TbDict productTypeValue = dictFeignClient.getProductTypeValue(productType);
            searchItem.setProductType(productTypeValue.getName());

            String repaymentWay = tbProduct.getRepaymentWay();
            TbDict tbDict = dictFeignClient.RepaymentWayByValue(repaymentWay);
            searchItem.setRepaymentWay(tbDict.getName());

            return searchItem;
        }).collect(Collectors.toList());



    }
}
